package com.cndw.kungfu.model.pet;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;

import com.cndw.kungfu.config.ConstantsConfig;
import com.cndw.kungfu.config.ConstantsSystem;
import com.cndw.kungfu.dao.PetDao;
import com.cndw.kungfu.domain.Pet;
import com.cndw.kungfu.domain.PetMode;
import com.cndw.kungfu.ext.LogUtil;
import com.cndw.kungfu.ext.NumberProcesser;
import com.cndw.kungfu.ext.TimeProcesser;
import com.cndw.kungfu.model.Context;
import com.cndw.kungfu.model.pet.domain.PetSoul;

@Component
public class PetManager {

	@Autowired
	private PetDao dao;

	private static int currentAutoNumber = -1;

	private synchronized long getNextPetId() {
		if (currentAutoNumber < 0) {
			long currentUnionId = 0;
			try {
				currentUnionId = dao.getMaxPetId();
			} catch (NullPointerException e) {

			} catch (Exception e) {
				e.printStackTrace();
			}
			currentAutoNumber = (int) (currentUnionId / 10000);
		}
		currentAutoNumber++;
		return currentAutoNumber * 10000 + 10000 - ConstantsConfig.getSysCgAutoNumberSuffix();
	}

	public Pet insert(long playerId, int modeId,int growth) {
		Pet pet = new Pet();
		pet.setId(getNextPetId());
		pet.setPlayerId(playerId);		
		pet.setModeId(modeId);	
		pet.setLevel(1);
		pet.setGrowth(growth);
		int start = growth / 100;
		start = NumberProcesser.between(start, 1, 3);
		pet.setStar(start);
		pet.setSpirit(0);
		pet.setPerception(0);
		
		PetMode petMode = Context.getPetServer().getPetMode(modeId);
		pet.setName(petMode.getName());	
		
		pet.clacPropertys();//计算宠物属性
		
		pet.setHp(pet.getMaxHp());
		pet.setMp(pet.getMaxMp());
		
		pet.setCreateTime(TimeProcesser.getUnixTime());		
		try {// 插入数据库,并设置用户id
			dao.insert(pet);
			return pet;
		}catch (DuplicateKeyException e) {
			LogUtil.getMain().error(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}
	
	public Map<Long, Pet> getPetsDB(long playerId){
		try {
			return dao.getPets(playerId);
		} catch (Exception e) {
			
		}
		return null;
	}

	public List<PetMode> getPetModesDB() {
		try {
			return dao.getPetModes();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public List<PetSoul> getPetSoulsDB(){
		try {
			return dao.getPetSouls();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	

	public boolean save(Pet pet) {
		try {
			if (pet.getPlayerId() <= 0 ) {
				dao.delete(pet.getId());
			}else {
				dao.update(pet);
			}			
		} catch (Exception e) {
			ConstantsSystem.throwExceptionDB(e);
			return false;
		}
		return true;
	}

}
